package com.bwie.filter;

import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @Author: yiang
 * @Date: 2025/10/9 15:22
 * @Description:
 **/
@Component
public class MyFilter implements GatewayFilter {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //请求
        ServerHttpRequest request = exchange.getRequest();
        //响应
        ServerHttpResponse response = exchange.getResponse();
        //获取token
        String token = request.getHeaders().getFirst("token");

        //拦截
        if(token==null){
            response.setComplete();
        }

        //解析token
        String userPhone = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("userPhone", String.class);

        //续期token 15分钟
        redisTemplate.expire("token-"+userPhone,15, TimeUnit.MINUTES);
        return chain.filter(exchange);
    }
}
